package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.controller.utils.R;
import com.itheima.domain.Book;
import com.itheima.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 陆小根
 * date: 2022/05/07
 * Description:
 */
@RestController
@RequestMapping("/books")
public class BookController {

  private final IBookService bookService;

  @Autowired
  public BookController(IBookService bookService) {
    this.bookService = bookService;
  }

  /**
   * 获取所有图书信息
   * @return
   */
  @GetMapping
  public R getAll() {
    return new R(true,bookService.list());
  }

  /**
   * 新增图书
   * @param book
   * @return
   */
  @PostMapping
  public R save(@RequestBody Book book) {
    boolean flag = bookService.save(book);
    return new R(flag, flag ? "添加成功^_^":"添加失败-_-!");
  }

  /**
   * 修改图书信息
   * @param book
   * @return
   */
  @PutMapping
  public R update(@RequestBody Book book) {
    boolean flag = bookService.updateById(book);
    return new R(flag,flag ? "修改成功^_^":"修改失败-_-!");
  }

  /**
   * 根据图书编号删除图书
   * @param id
   * @return
   */
  @DeleteMapping("{id}")
  public R delete(@PathVariable("id") Integer id) {
    boolean flag = bookService.removeById(id);
    return new R(flag, flag ? "删除成功^_^":"删除失败-_-!");
  }

  /**
   * 根据图书编号查询图书信息
   * @param id
   */
  @GetMapping("{id}")
  public R getById(@PathVariable("id") Integer id) {
    Book book = bookService.getById(id);
    return new R(true, book);

  }


  /**
   * 分页查询功能
   * @param currentPage
   * @param pageSize
   * @return
   */
  /*@GetMapping("{currentPage}/{pageSize}")
  public R getPage(@PathVariable("currentPage") int currentPage,
                   @PathVariable("pageSize") int pageSize) {
    IPage<Book> page = bookService.getPage(currentPage, pageSize);
    // 如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
    if (currentPage > page.getPages()) {
      page = bookService.getPage((int)page.getPages(), pageSize);
    }
    return new R(true, page);
  }*/

  /**
   * 分页查询+条件查询
   * @param currentPage
   * @param pageSize
   * @return
   */
  @GetMapping("{currentPage}/{pageSize}")
  public R getPage(@PathVariable("currentPage") int currentPage,
                   @PathVariable("pageSize") int pageSize,
                   Book book) {
    System.out.println("参数book===>" + book);
    IPage<Book> page = bookService.getPage(currentPage, pageSize, book);
    // 如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
    if (currentPage > page.getPages()) {
      page = bookService.getPage((int)page.getPages(), pageSize, book);
    }
    return new R(true, page);
  }
}
